package controllers

import (
	"encoding/json"
	"hello/inits/myhelpers"
	"io"
	"net/http"
)

type Base struct {
}

//LayuiSuccessJson layui列表返回
func (b Base) LayuiSuccessJson(w http.ResponseWriter, data interface{}, msg string, count int) {
	returnData := getLayuiReturnData(count, data)
	w.Header().Set("content-type", "application/json")
	w.WriteHeader(http.StatusOK)
	json_data, _ := json.Marshal(returnData)
	io.WriteString(w, string(json_data))
	return
}

func (b *Base) SuccessJson(w http.ResponseWriter, data interface{}, msg string) {
	if msg == "" {
		msg = "success"
	}
	b.Json(w, data, 1, msg)
	return
}

func (b *Base) ErrorJson(w http.ResponseWriter, data interface{}, msg string) {
	if msg == "" {
		msg = "error"
	}
	b.Json(w, data, 0, msg)
	return
}

// 200响应码
func (b Base) Json(w http.ResponseWriter, data interface{}, code int, msg string) {
	b.ReturnJson(w, data, code, http.StatusOK, msg)
}

func (b Base) ReturnJson(w http.ResponseWriter, data interface{}, code int, httpcode int, msg string) {
	returnData := getReturnData(code, msg, data)
	w.Header().Set("content-type", "application/json")
	w.WriteHeader(httpcode)
	json_data, _ := json.Marshal(returnData)
	io.WriteString(w, string(json_data))
}

func (b Base) GetHelper() *myhelpers.Helper {
	return new(myhelpers.Helper)
}

func getReturnData(code int, msg string, data interface{}) interface{} {
	type ReturnMsg struct {
		Code int         `json:"code"`
		Msg  string      `json:"msg"`
		Data interface{} `json:"data"`
	}
	res := ReturnMsg{code, msg, data}
	return res
}

func getLayuiReturnData(count int, data interface{}) interface{} {
	type ReturnMsg struct {
		Code  int         `json:"code"`
		Msg   string      `json:"msg"`
		Count int         `json:"count"`
		Data  interface{} `json:"data"`
	}
	res := ReturnMsg{0, "", count, data}
	return res
}
